-- MAESS系统Redis初始化脚本
-- 初始化系统配置、缓存结构和监控数据

-- 系统配置哈希表
local system_configs = {
    -- 应用配置
    ['app:name'] = 'MAESS智能体系统',
    ['app:version'] = '1.0.0',
    ['app:debug'] = 'false',
    ['app:timezone'] = 'Asia/Shanghai',
    
    -- 数据库配置
    ['db:host'] = '192.168.64.100',
    ['db:port'] = '5432',
    ['db:name'] = 'maess_db',
    ['db:pool_size'] = '20',
    ['db:timeout'] = '30',
    
    -- Redis配置
    ['redis:host'] = '192.168.64.100',
    ['redis:port'] = '6379',
    ['redis:db'] = '0',
    ['redis:pool_size'] = '50',
    ['redis:timeout'] = '10',
    
    -- 外部服务配置
    ['external:db:host'] = '192.168.64.100',
    ['external:redis:host'] = '192.168.64.100',
    ['external:api:host'] = '192.168.64.100',
    ['external:search:host'] = '192.168.64.100',
    ['external:monitor:host'] = '192.168.64.100',
    
    -- 工作流配置
    ['workflow:max_instances'] = '100',
    ['workflow:max_retries'] = '3',
    ['workflow:default_timeout'] = '300',
    ['workflow:concurrent_limit'] = '10',
    
    -- 任务配置
    ['task:max_retries'] = '3',
    ['task:retry_delay'] = '60',
    ['task:timeout'] = '300',
    ['task:concurrent_limit'] = '5',
    
    -- 监控配置
    ['monitoring:enabled'] = 'true',
    ['monitoring:interval'] = '60',
    ['monitoring:retention_days'] = '7',
    
    -- 告警配置
    ['alerts:enabled'] = 'true',
    ['alerts:email_enabled'] = 'true',
    ['alerts:webhook_enabled'] = 'false',
    ['alerts:threshold:cpu'] = '80',
    ['alerts:threshold:memory'] = '85',
    ['alerts:threshold:disk'] = '90',
    
    -- 熔断器配置
    ['circuit_breaker:enabled'] = 'true',
    ['circuit_breaker:failure_threshold'] = '5',
    ['circuit_breaker:recovery_timeout'] = '60',
    ['circuit_breaker:half_open_max_calls'] = '3',
    
    -- 分布式锁配置
    ['distributed_lock:enabled'] = 'true',
    ['distributed_lock:default_ttl'] = '300',
    ['distributed_lock:renew_interval'] = '60',
    
    -- 搜索配置
    ['search:enabled'] = 'true',
    ['search:index_refresh_interval'] = '300',
    ['search:max_results'] = '100',
    ['search:min_score'] = '0.1',
    
    -- 缓存配置
    ['cache:ttl:default'] = '3600',
    ['cache:ttl:session'] = '86400',
    ['cache:ttl:workflow'] = '7200',
    ['cache:ttl:metrics'] = '300',
    
    -- 限流配置
    ['rate_limit:enabled'] = 'true',
    ['rate_limit:requests_per_minute'] = '100',
    ['rate_limit:requests_per_hour'] = '1000',
    ['rate_limit:burst_size'] = '10'
}

-- 批量设置系统配置
for key, value in pairs(system_configs) do
    redis.call('HSET', 'maess:config', key, value)
end

-- 初始化监控指标结构
local metrics_structure = {
    -- 系统指标
    'system:cpu:usage',
    'system:memory:usage', 
    'system:disk:usage',
    'system:network:io',
    'system:process:count',
    
    -- 应用指标
    'app:requests:total',
    'app:requests:success',
    'app:requests:error',
    'app:requests:duration',
    'app:active:users',
    'app:active:sessions',
    
    -- 工作流指标
    'workflow:instances:total',
    'workflow:instances:running',
    'workflow:instances:success',
    'workflow:instances:failed',
    'workflow:instances:duration',
    
    -- 任务指标
    'task:instances:total',
    'task:instances:running',
    'task:instances:success',
    'task:instances:failed',
    'task:instances:retries',
    
    -- 数据库指标
    'db:connections:active',
    'db:connections:idle',
    'db:queries:total',
    'db:queries:slow',
    'db:transactions:total',
    
    -- Redis指标
    'redis:connections:active',
    'redis:memory:usage',
    'redis:commands:total',
    'redis:keys:total',
    'redis:hit_ratio',
    
    -- 外部服务指标
    'external:api:requests:total',
    'external:api:requests:success',
    'external:api:requests:error',
    'external:api:requests:duration',
    'external:db:connections:active',
    'external:redis:connections:active'
}

-- 初始化指标结构
for _, metric_key in ipairs(metrics_structure) do
    redis.call('HSET', 'maess:metrics:current', metric_key, '0')
    redis.call('HSET', 'maess:metrics:previous', metric_key, '0')
end

-- 初始化告警状态
local alert_keys = {
    'alert:system:cpu:high',
    'alert:system:memory:high',
    'alert:system:disk:high',
    'alert:app:error:rate:high',
    'alert:app:response:time:high',
    'alert:db:connection:high',
    'alert:redis:memory:high',
    'alert:external:api:failure:high',
    'alert:workflow:failure:high',
    'alert:task:failure:high'
}

for _, alert_key in ipairs(alert_keys) do
    redis.call('HSET', 'maess:alerts:status', alert_key, 'inactive')
    redis.call('HSET', 'maess:alerts:last_triggered', alert_key, '0')
end

-- 初始化熔断器状态
local circuit_breakers = {
    'circuit_breaker:database',
    'circuit_breaker:redis',
    'circuit_breaker:external_api',
    'circuit_breaker:search_engine'
}

for _, breaker_name in ipairs(circuit_breakers) do
    redis.call('HSET', 'maess:circuit_breakers', breaker_name, 'closed')
    redis.call('HSET', 'maess:circuit_breakers:failures', breaker_name, '0')
    redis.call('HSET', 'maess:circuit_breakers:successes', breaker_name, '0')
    redis.call('HSET', 'maess:circuit_breakers:last_failure', breaker_name, '0')
    redis.call('HSET', 'maess:circuit_breakers:last_success', breaker_name, '0')
end

-- 初始化分布式锁状态
redis.call('DEL', 'maess:distributed_locks:active')

-- 初始化搜索索引状态
redis.call('HSET', 'maess:search:indexes', 'documents:count', '0')
redis.call('HSET', 'maess:search:indexes', 'documents:last_updated', '0')
redis.call('HSET', 'maess:search:indexes', 'index:status', 'ready')

-- 初始化工作流队列
local workflow_queues = {
    'maess:queue:workflow:pending',
    'maess:queue:workflow:running',
    'maess:queue:workflow:completed',
    'maess:queue:workflow:failed'
}

for _, queue_name in ipairs(workflow_queues) do
    redis.call('DEL', queue_name)
end

-- 初始化任务队列
local task_queues = {
    'maess:queue:task:pending',
    'maess:queue:task:running', 
    'maess:queue:task:completed',
    'maess:queue:task:failed',
    'maess:queue:task:retry'
}

for _, queue_name in ipairs(task_queues) do
    redis.call('DEL', queue_name)
end

-- 初始化Celery队列
local celery_queues = {
    'celery',
    'celery:workflow',
    'celery:task',
    'celery:monitoring',
    'celery:alerts'
}

for _, queue_name in ipairs(celery_queues) do
    redis.call('DEL', queue_name)
end

-- 设置系统启动时间
redis.call('SET', 'maess:system:startup_time', tostring(redis.call('TIME')[1]))

-- 设置最后更新时间
redis.call('SET', 'maess:system:last_updated', tostring(redis.call('TIME')[1]))

-- 设置初始化完成标志
redis.call('SET', 'maess:system:initialized', 'true')
redis.call('SET', 'maess:system:status', 'ready')

-- 返回初始化状态
local result = {
    ['initialized'] = true,
    ['startup_time'] = redis.call('GET', 'maess:system:startup_time'),
    ['config_count'] = redis.call('HLEN', 'maess:config'),
    ['metrics_count'] = redis.call('HLEN', 'maess:metrics:current'),
    ['alerts_count'] = redis.call('HLEN', 'maess:alerts:status'),
    ['circuit_breakers_count'] = redis.call('HLEN', 'maess:circuit_breakers'),
    ['status'] = 'initialization_completed'
}

return cjson.encode(result)